let MS = require('./ms')
const fetch = "xxrequire('@system.fetch')xx"

const setHeader = (config) => {
  let header = {
    'content-type': 'application/json',
    'X-Bmob-SDK-Type': 'wechatApp'
    // 'X-Bmob-Application-Id': config.applicationId,
    // 'X-Bmob-REST-API-Key': config.applicationKey
  }
  // if (config.applicationMasterKey) {
  //   header['X-Bmob-Master-Key'] = config.applicationMasterKey
  // }
  return header
}

const request = (route, method = 'get', parma = {}, data = {}) => {
  return new Promise((resolve, reject) => {
    const header = setHeader(MS._config)

    // if (undefined === MS.User) {
    //     MS = require('./ms')
    // }
    // var current = MS.User.current()
    // if (current) {
    //   header['X-Bmob-Session-Token'] = current.sessionToken
    // }

    fetch.fetch({
      url: route,
      header: header,
      method: method,
      data: parma,
      success: function (res) {
        const data = JSON.parse(res.data)
        if (data.code) {
          reject(data)
        }
        resolve(data)
      },
      fail: function (data, code) {
        console.log(`handling fail, code = ${code}`)
        reject(data)
      }
    })
  })
}
module.exports = request
